import wepy from 'wepy'

export default class Home extends wepy.mixin {
  data = {
    value: '',
    suggestList: [],
    setId: 0,
    // 搜索历史数据
    history: []
  }

  config = {
  }

  methods = {
    // 搜索输入框发生变化
    onChange (e) {
      this.value = e.detail.trim()
      // 实现搜索的功能
      clearTimeout(this.setId)
      if(this.value === '') return this.suggestList=[]
      this.setId = setTimeout(async ()=>{
        const { data: res } = await wepy.get('/goods/qsearch',{
          query: this.value
        })
        if(res.meta.status !== 200) return wepy.baseToast()
        this.suggestList = res.message
        this.$apply()
      },800)
    },

    // 手机上：点击了搜索按钮，模拟器：敲回车
    onSearch () {
      clearTimeout(this.setId)
      if(this.value === '') return 
      if(this.history.indexOf(this.value) === -1){
        this.history.unshift(this.value)
        this.history = this.history.slice(0,10)
        wepy.setStorageSync('history',this.history)
      }
      wepy.navigateTo({
        url: '/pages/goods_list?query='+this.value
      })
    },

    // 点击删除历史
    removeHistory () {
      this.history = []
      wepy.setStorageSync('history',[])
    }
  }

  onLoad () {
    this.history = wepy.getStorageSync('history') || []
  }

  onHide () {
    setTimeout(()=>{
      this.value = ''
      this.suggestList = []
    },1000)
  }

  onShow () {
    this.$parent.setTabbarBadge()
  }
}